package org.example.carsystem.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.sun.deploy.net.URLEncoder;
import org.example.carsystem.domain.SysUser;

import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public abstract class ExportUtils {

    /**
     * response
     * name 文件名
     * sheet sheet名
     * list 数据集合
     * */
    public static void export(HttpServletResponse response, String name, String sheet, List list) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SysUser.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet(sheet).doWrite(list);
    }

    /**
     * response
     * name 设定输出文件头名称
     * url 模板地址
     * 导出导入所需模板*/
    public static void doLoadTemplate(HttpServletResponse response, String name,String url){
        try {
            // 清空输出流
            response.reset();
            String resultFileName = name + ".xlsx";
            resultFileName = URLEncoder.encode(resultFileName,"UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型
            //输入流：文件路径   // 本地路径：
            DataInputStream in = new DataInputStream(new FileInputStream(url));
            //输出流
            OutputStream out = response.getOutputStream();
            //输出文件
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            // 清空输出流
            response.reset();
        }
    }
}
